package cn.klaw.i18n.provider;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import cn.klaw.base.UserInfo;
import cn.klaw.util.UserProvider;
import cn.klaw.base.ActionResult;
import cn.klaw.i18n.constant.I18nApiConst;
import cn.klaw.util.Constants;
import cn.klaw.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;

import java.util.Locale;
import java.util.Objects;

/**
 * 国际化翻译源提供者
 */
@Slf4j
public class MyDynamicMessageProvider implements DynamicMessageProvider {

    private int timeout = 3000;

    @Override
    public String getI18nList(Locale locale) {
        UserInfo userInfo = UserProvider.getUser();
        String token = userInfo.getToken();
        if(StringUtil.isNotEmpty(token)) {
            try (HttpResponse httpResponse = HttpRequest.get(I18nApiConst.i18nListUrl)
                    .timeout(timeout)
                    .setReadTimeout(timeout)
                    .setConnectionTimeout(timeout)
                    .header(Constants.AUTHORIZATION, token)
                    .header(HttpHeaders.ACCEPT_LANGUAGE, locale.toLanguageTag())
                    .execute()) {
                if (httpResponse.isOk()) {
                    String result = httpResponse.body();
                    ActionResult<JSONArray> out = JSON.parseObject(result, new TypeReference<ActionResult<JSONArray>>() {});
                    if (Objects.equals(Constants.SUCCESS, out.getCode())) {
                        JSONArray messages = out.getData();
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < messages.size(); i++) {
                            JSONObject obj = messages.getJSONObject(i);
                            String code = obj.getString("enCode");
                            String msg = obj.getString("fullName");
                            stringBuilder.append(String.format("%s=%s%n", code, msg));
                        }
                        return stringBuilder.toString();
                    }
                }
            } catch (Exception e) {
                log.error("语言翻译内容获取失败: {}", e.getMessage());
            }
        }
        return null;
    }
}
